const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 显示繁忙提示
var showBusy = text => wx.showToast({
  title: text,
  icon: 'loading',
  duration: 90000
})

// 显示成功提示
var showSuccess = text => wx.showToast({
  title: text,
  icon: 'success'
})

// 显示失败提示
var showModel = (title, content) => {
  wx.hideToast();

  wx.showModal({
    title,
    content: JSON.stringify(content),
    showCancel: false
  })
}
function checkNumber(theObj) {
  var reg = /^[1-9]+?[1-9]*$/;
  if (reg.test(theObj)) {
    return true;
  }
  return false;
};
function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
};
/**
 * 将小程序的API封装成支持Promise的API
 * @params fn {Function} 小程序原始API，如wx.login
 */
function MyPromise(fn){
  return (obj={}) =>{
    return new Promise( (resolve,reject)=>{
      obj.success = res =>{
        resolve(res);
      }
      obj.fail = res =>{
        reject(res);
      }
      fn(obj)
    })
  }
}
function request() {
  return MyPromise(wx.request);
}

// var MyPromise = (api) => {
//   return (options, ...params) => {
//     return new Promise((resolve, reject) => {
//       api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
//     });
//   }
// }

module.exports = {
  formatTime: formatTime,
  showBusy: showBusy,
  showSuccess: showSuccess,
  showModel: showModel,
  checkNumber: checkNumber,
  uuid: uuid,
  MyPromise: MyPromise,
  request: request
}
